package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiContractEntity;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessRelatedDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasProcessRelatedDataModel;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ContractDao;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.product.ContractProductEnum;
import com.xbongbong.saas.enums.product.RefundProductEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.ContractSubDataModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getLongOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getStringOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;


/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/23 14:43
 * @since v1.0
 */
@Service("contractModel")
public class ContractModelImpl implements ContractModel {
    private static final Logger LOG = LoggerFactory.getLogger(ContractModelImpl.class);

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private ContractDao contractDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ContractSubDataModel contractSubDataModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasProcessRelatedDataModel paasProcessRelatedDataModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private EsHelper esHelper;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(ContractEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        StandardizeDataUtil.standardizeNotString(entity);

        Integer success = contractDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT);
        // 此处改为不等待，有一家客户（ding1756f8c284bb5edea1320dcb25e91351）的业务规则是合同订单改合同订单，需要等待es才可以查到
        insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.WAIT_UNTIL);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        return success;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(ContractEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = contractDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = contractDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            paasFormDataEntity.setCreatorId(null);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }


        return success;
    }

    @Override
    public List<ContractEntityExt> findEntitys(Map<String, Object> param) {
        List<ContractEntityExt> entitys = contractDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return contractDao.getEntitysCount(param);
    }

    /**
     * 根据data里某个条件搜索
     *
     * @param attr   data里属性
     * @param value  data里属性的值
     * @param param 参数
     */
    @Override
    public Integer getCountByOneCondition(String attr, Object value, Map<String, Object> param) {
        attr = "$." + attr;
        return contractDao.getCountByOneCondition(attr, value, param);
    }

    @Override
    public ContractEntityExt getByKey(Long key, String corpid) {
        ContractEntityExt contractEntityExt = contractDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(contractEntityExt), IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        return contractEntityExt;
    }

    @Override
    public List<ContractEntityExt> getContractByDeadlineTime(String corpid, Long startDeadlineTime, Long endDeadlineTime) {
        List<ContractEntityExt> contractEntityExts = contractDao.getContractByDeadlineTime(corpid, startDeadlineTime, endDeadlineTime);
        paasFormSubDataModel.findSubEntity(corpid, contractEntityExts, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        return contractEntityExts;
    }

    /**
     * 联系人产品数据保存
     *
     * @param contract 供应商实体
     * @return Integer
     * @author Jian.Wang
     * @date 2019/1/23 20:27
     * @since v1.0
     */
    @Override
    public Integer save(ContractEntityExt contract) throws XbbException {
        if (contract.getId() == null || contract.getId() == 0L) {
            return insert(contract);
        } else {
            return update(contract);
        }
    }

    @Override
    public ContractEntityExt getLatestEntityByCustomerId(String corpid, Long customerId) throws XbbException {

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.LINK_CUSTOMER), customerId));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.sort(ContractEnum.getEsAttr4Keyword(ContractEnum.SIGN_TIME), SortOrder.DESC);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 1);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ContractEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, ContractEntityExt.class);
        List<ContractEntityExt> list = esEntities.getContent();
        ContractEntityExt contract = null;
        if (!list.isEmpty()) {
            contract = list.get(0);
        }

        return contract;
    }

    @Override
    public List<ContractEntityExt> getLatestEntityListByCustomerId(String corpid, Long customerId) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.LINK_CUSTOMER), customerId));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.sort(ContractEnum.getEsAttr4Keyword(ContractEnum.SIGN_TIME), SortOrder.DESC);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 2);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ContractEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, ContractEntityExt.class);
        return esEntities.getContent();
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = contractDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CONTRACT);
        }
        if (!subList.isEmpty()) {
            contractSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatchImmediately(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = contractDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CONTRACT, WriteRequest.RefreshPolicy.NONE);
        }
        if (!subList.isEmpty()) {
            contractSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid,boolean needThrow) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = contractDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CONTRACT,needThrow);
        }
        if (!subList.isEmpty()) {
            contractSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = contractDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_CONTRACT, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            contractSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> deleteIdIn, String corpid) throws XbbException{
        Integer integer = contractDao.deleteBatch(deleteIdIn, corpid);
        paasEsModel.deleteBatch(deleteIdIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_CONTRACT);
        paasFormSubDataModel.deleteBatchByDataId(deleteIdIn, corpid, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.CONTRACT, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_CONTRACT);
        paasEsModel.delete(deleteDTO);
        Integer integer = contractDao.deleteByKey(key, corpid);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        return integer;
    }

    @Override
    public List<String> getContractJsonExtractListByIn(String corpid, List<String> contractIds, String attr) {
        attr = "$." + attr;
        return contractDao.getContractJsonExtractListByIn(corpid, contractIds, attr);
    }

    @Override
    public List<AiContractEntity> getContractList4Ai(String corpid, List<Long> idIn) {
        return contractDao.getContractList4Ai(corpid, idIn);
    }

    @Override
    public List<ContractEntityExt> findEntitysByIdIn(String corpid,Integer del,List<Long> idIn){
        List<ContractEntityExt> contractEntityExts = contractDao.findEntitysByIds(corpid, BasicConstant.ZERO, idIn);
        paasFormSubDataModel.findSubEntity(corpid, contractEntityExts, IndexTypeEnum.IDX_SAAS_CONTRACT_SUB);
        return contractEntityExts;
    }

    @Override
    public List<ContractEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return contractDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> entities = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        Boolean isJxcUse = paasAppModel.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
        boolean unitNoEdit = false;
        if (Objects.nonNull(dataEntity) && !Objects.equals(formatExplainDTO.getFromCopy(), true)) {
            if (isJxcUse) {
                if (CollectionsUtil.isEmpty(dataEntity.getData().getJSONArray(ContractEnum.OUTSTOCK_ID.getAttr()))) {
                    //校验审批中是否有下游出库单
                    if (commonHelp.isOpenWorkFlow(corpid)) {
                        List<PaasFormDataEntityExt> approvalPaasFormDataList = outstockModel.findOutstockList(corpid, OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode(), dataEntity.getId(),
                                Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()), Arrays.asList(FieldTypeEnum.DATAID.getAlias()));
                        if (!approvalPaasFormDataList.isEmpty()) {
                            unitNoEdit = true;
                        }
                    } else {
                        List<PaasProcessRelatedDataEntity> paasProcessRelatedDataEntities = paasProcessRelatedDataModel.getByRefIdAndBusinessType(dataEntity.getId(), XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), corpid);
                        if (!paasProcessRelatedDataEntities.isEmpty()) {
                            unitNoEdit = true;
                        }
                    }
                } else {
                    unitNoEdit = true;
                }
            } else {
                if (!Objects.equals(dataEntity.getData().getInteger(ContractEnum.HAS_RED.getAttr()), 1)) {
                    //校验审批中是否有下游退货单
                    if (!commonHelp.isOpenWorkFlow(corpid)) {
                        List<PaasProcessRelatedDataEntity> paasProcessRelatedDataEntities = paasProcessRelatedDataModel.getByRefIdAndBusinessType(dataEntity.getId(), XbbRefTypeEnum.REFUND.getCode(), corpid);
                        if (!paasProcessRelatedDataEntities.isEmpty()) {
                            unitNoEdit = true;
                        }
                    } else {
                        BoolQueryBuilder boolQueryBuilder = boolQuery();
                        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
                        boolQueryBuilder.filter(termQuery(esData + RefundEnum.CONTRACT_ID.getAttr(), dataEntity.getId()));
                        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
                        boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                        List<PaasFormDataEntityExt> approvalRefundList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_REFUND, boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(FieldTypeEnum.DATAID.getAlias()));
                        if (!approvalRefundList.isEmpty()) {
                            unitNoEdit = true;
                        }
                    }
                } else {
                    unitNoEdit = true;
                }
            }
        }
        for (FieldAttrEntity fieldAttrEntity : entities) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, ContractEnum.LINK_CUSTOMER.getAttr())) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, ContractEnum.PRODUCT.getAttr())) {
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.CONTRACT, corpid, BasicConstant.ONE, unitNoEdit);
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.ADD_PAYMENT.getAttr()) &&
                    !formatExplainDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PAYMENT_ADD.getAlias())) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.PRODUCT_TOTAL.getAttr())) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType()) && (Objects.isNull(formatExplainDTO.getFromCopy()) || !formatExplainDTO.getFromCopy())) {
                fieldAttrEntity.setEditable(0);
                fieldAttrEntity.setMemo(I18nMessageUtil.getMessage(I18nStringConstant.FILL_IN_FEEDBACK_MEMO));
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4ShowBySource(result, ContractEnum.LINK_CUSTOMER.getAttr(), ContractEnum.LINK_CUSTOMER_HIDE.getAttr(), ContractEnum.LINK_CUSTOMER.getFieldType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CONTRACT.getCode(), formDataUpdateGetDTO.getCorpid());
        showFormatHelp.formatLinkBusiness4Show(result, ContractEnum.LINK_CUSTOMER.getAttr(), ContractEnum.LINK_CUSTOMER_HIDE.getAttr(), ContractEnum.LINK_CUSTOMER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ContractEnum.LINK_CONTACT.getAttr(), ContractEnum.LINK_CONTACT_HIDE.getAttr(), ContractEnum.LINK_CONTACT.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ContractEnum.LINK_OPPORTUNITY.getAttr(), ContractEnum.LINK_OPPORTUNITY_HIDE.getAttr(), ContractEnum.LINK_OPPORTUNITY.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ContractEnum.LINK_PARTNER_CUSTOMER.getAttr(), ContractEnum.LINK_PARTNER_CUSTOMER_HIDE.getAttr(), ContractEnum.LINK_PARTNER_CUSTOMER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ContractEnum.QUOTATION_ID.getAttr(), ContractEnum.QUOTATION_NAME.getAttr(), ContractEnum.QUOTATION_ID.getFieldType());
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        // 获取关联产品
        List<ContractProductEntity> conProductList = new ArrayList<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(ContractEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, ContractEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArr);
                getProductList(corpid, conProductList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(ContractEnum.PRODUCT.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        ContractProductEntity contractProductEntity = new ContractProductEntity();
                        contractProductEntity.setCorpid(corpid);
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            contractProductEntity.setId(subProductId);
                        }
                        contractProductEntity.setProductId(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()));
                        contractProductEntity.setData(jsonObject);
                        conProductList.add(contractProductEntity);
                    }
                }
            }
        } else {
            conProductList = contractProductModel.getProductsByConId(dataId, corpid, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
        }
        List<Long> productIdList = new ArrayList<>();
        conProductList.forEach(item -> {
            productIdList.add(item.getProductId());
        });
        Map<Long, ProductEntityExt> productMap = productModel.getProductMapByIds(corpid, productIdList, DelEnum.NORMAL.getDel(),
                Arrays.asList(StringConstant.SAAS_LINK_BUSINESS_ID,
                        ProductEnum.getAttrConnectData(ProductEnum.STOCK),
                        ProductEnum.getAttrConnectData(ProductEnum.NAME),
                        ProductEnum.getAttrConnectData(ProductEnum.ONLINE),
                        ProductEnum.getAttrConnectData(ProductEnum.ENABLE_MULTI_UNIT)));
        Set<Long> multiUnitProductIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productMap.forEach((key, value) -> {
            if (Objects.equals(value.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1)) {
                multiUnitProductIds.add(key);
            }
        });
        Map<Long, List<MultiUnitPricePoJo>> priceMap = productUnitPriceModel.getPriceMapByProductIdSet(corpid, multiUnitProductIds);
        // 老数据没有产品的库存数量，需要实时查询
        Iterator iterator = conProductList.iterator();
        // fix:修复下架多个产品后也只显示一个，将hashset改为arraylist
        List<String> offlinedProducts = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        while (iterator.hasNext()) {
            ContractProductEntity conProduct = (ContractProductEntity) iterator.next();
            JSONObject conProductData = conProduct.getData();
            Long productId = conProductData.getLong(ContractProductEnum.PRODUCT.getAttr());
            ProductEntityExt productEntityExt = productMap.get(productId);
            if (Objects.isNull(productEntityExt)) {
                continue;
            }
            if (Objects.nonNull(priceMap.get(productId))) {
                conProduct.setProductPriceArr(JSONArray.parseArray(JSONArray.toJSONString(priceMap.get(productId))));
            }
            JSONObject productData = productEntityExt.getData();
            if (!conProductData.containsKey(ContractProductEnum.STOCK.getAttr())) {
                if (Objects.isNull(productData.get(ProductEnum.STOCK.getAttr()))) {
                    conProductData.put(ContractProductEnum.STOCK.getAttr(), BasicConstant.ZERO);
                } else {
                    conProductData.put(ContractProductEnum.STOCK.getAttr(), productData.get(ProductEnum.STOCK.getAttr()));
                }
            }
            if (Objects.equals(updateDataTypeEnum, UpdateDataTypeEnum.COPY)) {
                // 下架产品剔除掉
                Integer online = productData.getInteger(ProductEnum.ONLINE.getAttr());
                String name = productData.getString(ProductEnum.NAME.getAttr());
                if (!Objects.equals(1, online)) {
                    offlinedProducts.add(name);
                    iterator.remove();
                }
            }
        }
        data.put(BasicConstant.OFF_LINED_PRODUCTS, offlinedProducts);
        formatProduct4Show3(conProductList, data, updateDataTypeEnum);
    }

    @Override
    public void formatProduct4Show3(List<ContractProductEntity> contractProductEntityList, JSONObject productData, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        JSONArray productArray = new JSONArray();
        for (ContractProductEntity contractProductEntity : contractProductEntityList) {
            JSONObject json = formatSingleProduct(contractProductEntity);
            if (updateDataTypeEnum.isUpdate() || updateDataTypeEnum.isDetail()) {
                json.put(BusinessConstant.PRODUCT_SUB_ID, contractProductEntity.getId());
                if (Objects.isNull(contractProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID, 0);
                }
            } else {
                json.put(BusinessConstant.PRODUCT_SUB_ID, 0);
            }
            json.put("refId", contractProductEntity.getSort());
            if (updateDataTypeEnum.isLinkAdd()) {
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(contractProductEntity.getCorpid(), contractProductEntity.getProductUnit()));
                json.put(BusinessConstant.RELY_PRODUCT_SUB_ID, contractProductEntity.getId());
                json.put("contractId",contractProductEntity.getContractId());
                json.put("productId",contractProductEntity.getProductId());
                json.put("contractProductId",contractProductEntity.getId());
            }
            productArray.add(json);
        }
        productData.put(ContractEnum.PRODUCT.getAttr(), productArray);
    }

    @Override
    public JSONObject formatSingleProduct(ContractProductEntity entity) {
        JSONObject json = entity.getData();
        Double rate = showFormatHelp.approvalSetBusinessUnit(json, entity);
        if (Objects.isNull(json) || json.isEmpty()) {
            json = new JSONObject();
            for (ContractProductEnum contractProductEnum : ContractProductEnum.values()) {
                String attr = contractProductEnum.getAttr();
                switch (contractProductEnum) {
                    case PRODUCT:
                        json.put(attr, entity.getProductId());
                        break;
                    case DISCOUNT:
                        json.put(attr, entity.getDiscount());
                        break;
                    case SELLING_PRICE:
                        json.put(attr, entity.getPrice());
                        break;
                    case NUM:
                        json.put(attr, Math.abs(entity.getProductNum()));
                        break;
                    case MEMO:
                        json.put(attr, entity.getMemo());
                        break;
                    case SUBTOTAL:
                        json.put(attr, Math.abs(entity.getProductNum()) * entity.getPrice() * entity.getDiscount() * 0.01);
                        break;
                    case STOCK:
                        break;
                    case UNIT:
                        json.put(attr, entity.getProductUnit());
                        break;
                    case PRICE:
                        json.put(attr, entity.getHistoricalPrice());
                        break;
                    default:
                        break;
                }
            }
        }
        if (Objects.nonNull(entity.getOutstockNum())) {
            json.put(ContractProductEnum.OUTSTOCK_NUM.getAttr(), Arith.div(entity.getOutstockNum(), rate));
        }
        if (Objects.nonNull(entity.getShipmentsNum())) {
            json.put(ContractProductEnum.SHIPMENTS_NUM.getAttr(), entity.getShipmentsNum());
        }
        Double num = Arith.sub(entity.getProductNum(), entity.getContractOutstockNum());
        Double waitOutstockNum = num >= 0 ? num : 0D;
        json.put(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr(), Arith.div(waitOutstockNum, rate));
        json.put(ContractProductEnum.RETURN_NUM.getAttr(), Arith.div(entity.getInstockNum() == null ? 0D : entity.getInstockNum(), rate));
        if (Objects.nonNull(entity.getProductPriceArr())) {
            json.put(ProductConstant.PRODUCT_PRICE, entity.getProductPriceArr());
        }
        return json;
    }

    @Override
    public JSONObject formatSingleRefundProduct(ContractProductEntity entity) {
        JSONObject json = entity.getData();
        Double rate = showFormatHelp.approvalSetBusinessUnit(json, entity);
        if (Objects.isNull(json) || json.isEmpty()) {
            json = new JSONObject();
            for (ContractProductEnum contractProductEnum : ContractProductEnum.values()) {
                String attr = contractProductEnum.getAttr();
                switch (contractProductEnum) {
                    case PRODUCT:
                        json.put(attr, entity.getProductId());
                        break;
                    case DISCOUNT:
                        json.put(attr, entity.getDiscount());
                        break;
                    case SELLING_PRICE:
                        json.put(attr, entity.getPrice());
                        break;
                    case NUM:
                        json.put(attr, Math.abs(entity.getProductNum()));
                        break;
                    case MEMO:
                        json.put(attr, entity.getMemo());
                        break;
                    case SUBTOTAL:
                        json.put(attr, Math.abs(entity.getProductNum()) * entity.getPrice() * entity.getDiscount() * 0.01);
                        break;
                    case STOCK:
                        break;
                    case UNIT:
                        json.put(attr, entity.getProductUnit());
                        break;
                    case PRICE:
                        json.put(attr, entity.getHistoricalPrice());
                        break;
                    default:
                        break;
                }
            }
        }
        json.put(SelectProductEnum.SUBTOTAL.getAttr(), Arith.mul(entity.getPrice(), Math.abs(entity.getProductNum())));
        if (Objects.nonNull(entity.getInstockNum())) {
            json.put(RefundProductEnum.INSTOCK_NUM.getAttr(), Arith.div(entity.getInstockNum(), rate));
        }
        Double num = Arith.sub(Math.abs(entity.getProductNum()), entity.getInstockNum());
        Double waitInstockNum = num >= 0 ? num : 0D;
        json.put(RefundProductEnum.WAIT_INSTOCK_NUM.getAttr(), Arith.div(waitInstockNum, rate));
        return json;
    }

    @Override
    public void getProductList(String corpid, List<ContractProductEntity> conProductList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 折扣
            Double discount = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.SALE_DISCOUNT.getSaasAttr(), 0D);
            // 售价
            Double saleProductPrice = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.SALE_PRODUCT_PRICE.getSaasAttr(), 0D);
            // 备注
            String memo = getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            // 产品成本
            Double cost = getDoubleOrDefaultFromFormData(productArrayJSONObject, "estimateCost", 0D);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getSaasAttr(), 0D);
                ContractProductEntity productEntity = new ContractProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setProductUnit(unit);
                productEntity.setCorpid(corpid);
                productEntity.setParentId(parentId);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setSpecification(specification);
                productEntity.setDiscount(discount);
                productEntity.setPrice(saleProductPrice);
                productEntity.setCost(cost);
                productEntity.setMemo(memo);
                productEntity.setSort(sort);
                conProductList.add(productEntity);
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 业务异常
     * @author wujian
     * @date 2021/01/09 15:28
     */
    @Override
    public void formatDataForDistributor(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4ShowBySource(result, OrderEnum.LINK_DISTRIBUTOR.getAttr(), OrderEnum.LINK_CUSTOMER_HIDE.getAttr(), OrderEnum.LINK_DISTRIBUTOR.getFieldType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CONTRACT.getCode(), saasAnalysisDataDTO.getCorpid());
        showFormatHelp.formatLinkBusiness4Show(result, OrderEnum.LINK_PARTNER_RECEIVER.getAttr(), OrderEnum.LINK_PARTNER_RECEIVER_HIDE.getAttr(), OrderEnum.LINK_PARTNER_RECEIVER.getFieldType());
    }


    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = contractDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_CONTRACT);
        paasEsModel.update(insertDTO);
        return success;
    }

    @Override
    public void updateContractDate(List<Map<String, Object>> updateContractEntity, String corpid){
        StandardizeDataUtil.standardizeListMap(updateContractEntity);
        contractDao.updateContractDate(updateContractEntity, corpid);
    }

    @Override
    public <T> List<T> getContractListByLinkId(String corpid, Long linkId, ContractEnum contractEnum, Class<T> clazz) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(contractEnum), linkId));
        boolQueryBuilder.filter(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.IS_RED), 0));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, PaasConstant.ES_MAX_PAGE_SIZE);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<T> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, clazz);
        return esEntities.getContent();
    }

    @Override
    public Long getMaxId(Map<String, Object> param) {
        return contractDao.getMaxId(param);
    }

}
